<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.server_relay_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #alert-form="{}">
        <el-alert type="info" show-icon :closable="false">
          <template #title>
            <el-text size="small">服务端将筛选对应功能类型的Topic上报数据，并将数据转发至消费组。</el-text>
          </template>
        </el-alert>
      </template>
      <template #status="{ row }">
        <el-switch
            v-model="row.status"
            inline-prompt
            @change="slotChange(row)"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
        />
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/iot/server/serverRelay";
import {mapGetters} from "vuex";
import {validatenull} from "@/utils/validate";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogWidth: 500,
        labelWidth: 120,
        searchLabelWidth: 100,
        addBtnText: '创建订阅',
        column: [
          {
            label: "",
            labelWidth: 10,
            prop: "alert",
            type: "input",
            slot: true,
            hide: true,
            span: 24,
          },
          {
            label: "所属产品",
            prop: "productKey",
            type: "select",
            dicUrl: "/blade-iot/product/select",
            props: {
              label: "productName",
              value: "productKey"
            },
            width: 250,
            span: 24,
            filterable: true,
            search: true,
            rules: [{
              required: true,
              message: "请选择产品",
              trigger: "blur"
            }],
          },
          {
            label: "消费组",
            prop: "groupId",
            type: "select",
            dicUrl: "/blade-iot/server/group/select",
            dataType: "string",
            props: {
              label: "groupName",
              value: "groupId"
            },
            multiple: true,
            filterable: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入消费组id",
              trigger: "blur"
            }]
          },
          {
            label: "功能类型",
            prop: "features",
            type: 'select',
            dicUrl: "/blade-system/dict/dictionary?code=topic_feature",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            multiple: true,
            filterable: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择topic功能类型",
              trigger: "blur"
            }],
          },
          {
            label: "是否启用",
            prop: "status",
            type: "radio",
            dicUrl: "/blade-system/dict/dictionary?code=yes_no",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: 0,
            slot: true,
            display: false,
            width: 90,
            span: 24,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.server_relay_add, false),
        viewBtn: this.validData(this.permission.server_relay_view, false),
        delBtn: this.validData(this.permission.server_relay_delete, false),
        editBtn: this.validData(this.permission.server_relay_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.productKey = this.$route.query.productKey;
      if (!validatenull(this.productKey)) {
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === "productKey") {
            item.value = this.productKey;
            item.disabled = true;
            item.search = false;
            this.onLoad(this.page, this.productKey);
          }
        });
      } else {
        this.onLoad(this.page);
      }
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功,服务端将在60s内更新配置!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "订阅成功,服务端将在60s内更新配置!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    slotChange(row) {
      if (!row.id) {
        return;
      }
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "订阅成功,服务端将在60s内更新配置!"
        });
      }, error => {
        window.console.log(error);
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        productKey,
      } = this.query;

      let values = {
        ...params,
        productKey: !validatenull(this.productKey) ? this.productKey : productKey,
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
